#!/usr/bin/env python
# coding=utf-8
#
# Copyright 2012 F2E.im
# Do have a faith in what you're doing.
# Make your life a story worth telling.

import uuid
import hashlib
import image
# import StringIO
import time
import json
import re
# import urllib2
import urllib
import urllib
import tornado.web
import lib.jsonp
from io import BytesIO as StringIO
from PIL import Image
import os

from handler.base import *
# from lib.sendmail import send
from lib.variables import gen_random
from lib.gravatar import Gravatar
from form.user import *

def do_login(self, user_id):
    user_info = self.user_model.get_user_by_uid(user_id)
    user_id = user_info["uid"]
    self.session["uid"] = user_id
    self.session["username"] = user_info["username"]
    self.session["email"] = user_info["email"]
    self.session["password"] = user_info["password"]
    self.session.save()

    self.set_secure_cookie("user", str(user_id))

def do_logout(self):
    # destroy sessions
    self.session["uid"] = None
    self.session["username"] = None
    self.session["email"] = None
    self.session["password"] = None
    self.session.save()

    # destroy cookies
    self.clear_cookie("user")

def upload(self):
        user_info = self.current_user
        user_id = user_info["uid"]
        avatar_name = "%s" % uuid.uuid5(uuid.NAMESPACE_DNS, str(user_id))
        avatar_raw = self.request.files["avatar"][0]["body"]
        avatar_buffer = StringIO(avatar_raw)
        avatar = Image.open(avatar_buffer)
        upload_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static/accountImg')  #文件的暂存路径

        # crop avatar if it's not square
        avatar_w, avatar_h = avatar.size
        avatar_border = avatar_w if avatar_w < avatar_h else avatar_h
        avatar_crop_region = (0, 0, avatar_border, avatar_border)
        avatar = avatar.crop(avatar_crop_region)

        avatar_96x96 = avatar.resize((96, 96), Image.ANTIALIAS)
        avatar_48x48 = avatar.resize((48, 48), Image.ANTIALIAS)
        avatar_32x32 = avatar.resize((32, 32), Image.ANTIALIAS)
        avatar_96x96.save(upload_path+"/b_%s.png" % avatar_name, "PNG")
        avatar_48x48.save(upload_path+"/m_%s.png" % avatar_name, "PNG")
        avatar_32x32.save(upload_path+"/s_%s.png" % avatar_name, "PNG")
        result = self.user_model.set_user_avatar_by_uid(user_id, "%s.png" % avatar_name)



class LoginHandler(BaseHandler):
    def get(self, *args, **kwargs):
        do_logout(self)
        template_variables = {}
        template_variables['info'] = ''
        if 'errors' in kwargs.keys():
            template_variables['errors'] = kwargs['errors']
        self.render("user/login.html", **template_variables)


    def post(self, *args, **kwargs):
        template_variables = {}

        # validate the fields
        form = LoginForm(self)
        if not form.validate():
            errors = {'errors':form.errors}
            return self.get(**errors)
        # continue while validate succeed

        secure_password = hashlib.sha1(form.password.data.encode(encoding='utf-8')).hexdigest()
        secure_password_md5 = hashlib.md5(form.password.data.encode(encoding='utf-8')).hexdigest()
        user_info = self.user_model.get_user_by_email_and_password(form.email.data, secure_password)
        user_info = user_info or self.user_model.get_user_by_email_and_password(form.email.data, secure_password_md5)

        if(user_info):
            do_login(self, user_info["uid"])
            # update `last_login`
            updated = self.user_model.set_user_base_info_by_uid(user_info["uid"], {"last_login": time.strftime('%Y-%m-%d %H:%M:%S')})
            return self.redirect(self.get_argument("next", "/"))
        template_variables["errors"] = {"invalid_email_or_password": [u"邮箱或者密码不正确"]}
        return self.get(**template_variables)



class LogoutHandler(BaseHandler):
    def get(self,*args, **kwargs):
        do_logout(self)
        # redirect
        self.redirect(self.get_argument("next", "/"))



class RegisterHandler(BaseHandler):

    def get(self, *args, **kwargs):
        # do_logout(self)
        template_variables = {}
        template_variables['info'] = ''
        if 'errors' in kwargs.keys():
            template_variables['errors'] = kwargs['errors']
        self.render("user/register.html", **template_variables)

    def post(self, *args, **kwargs):
        form = RegisterForm(self)

        if not form.validate():
            errors = {'errors':form.errors}
            return self.get(**errors)

        if form.username.data in self.settings.get('reserved'):
            errors = {'errors':{}}
            errors['errors']['reserved'] = ['用户名被保留不可用']
            return self.get(**errors)

        secure_password = hashlib.sha1(form.password.data.encode(encoding='utf-8')).hexdigest()

        user_info = {
            "email": form.email.data,
            "password": secure_password,
            "username": form.username.data,
            "created": time.strftime('%Y-%m-%d %H:%M:%S')
        }

        if(self.current_user):
            return
        user_id = self.user_model.add_new_user(user_info)
        if user_id is 'isHave':
            errors = {'errors':{'username_or_email':['用户名或邮箱已占用']}}
            return self.get(**errors)
        if user_id:
            do_login(self, user_id)



class UcenterHandler(BaseHandler):
    def get(self, *args, **kwargs):
        return self.render('user/ucenter.html', **kwargs)


class AccountHandler(BaseHandler):
    def get(self, *args, **kwargs):
        return self.render('user/account.html', **kwargs)

    def post(self, *args, **kwargs):
        if self.request.files:
            upload(self)

        form = SettingForm(self)

        if not form.validate():
            self.get({"errors": form.errors})
            return

        # continue while validate succeed

        user_info = self.current_user
        update_result = self.user_model.set_user_base_info_by_uid(user_info["uid"], {
            "username": form.username.data,
            "nickname": form.nickname.data,
            "signature": form.signature.data,
            "location": form.location.data,
            "website": form.website.data,
            "company": form.company.data,
            "github": form.github.data,
            "twitter": form.twitter.data,
            "douban": form.douban.data,
            "self_intro": form.self_intro.data,
        })

        # update `updated`
        template_variables = {}
        template_variables["success_message"] = [u"用户基本资料更新成功"]
        updated = self.user_model.set_user_base_info_by_uid(self.current_user['uid'], {"updated": time.strftime('%Y-%m-%d %H:%M:%S')})
        return self.get(**template_variables)

